package com.foreknow.dao.impl;

import com.foreknow.bean.Guestbook;
import com.foreknow.bean.User;
import com.foreknow.dao.GuestbookDao;
import com.foreknow.db.DBManager;
import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactoy;

import javax.sql.rowset.spi.SyncResolver;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class GuestbookDaoImpl extends BaseDao implements GuestbookDao {
    @Override
    public boolean save(Guestbook guestbook) throws SQLException {
        String sql = "insert into guestbook(name,phone,email,title,content,createdtime) values(?,?,?,?,?,?)";
        int isRight = jdbcTemplate.update(sql,guestbook.getName(),guestbook.getPhone(),guestbook.getEmail(),guestbook.getTitle(),guestbook.getContent(),guestbook.getCreatedtime());
        return isRight == 1;
    }

    @Override
    public Guestbook selectid(int id) throws SQLException {
        String sql = "select * from guestbook where id = ?";
        EntityMapping mapping = mappingFactoy.getmapping(MappingFactoy.Guestbook_Mapping);
        List<Object> list = jdbcTemplate.query(sql,mapping,id);
        if (list.size()>0){
            Guestbook guestbook = (Guestbook) list.get(0);
            return guestbook;
        }
        return null;
    }

    @Override
    public List<Object> selectname(String name) throws SQLException{
        String sql = "select * from guestbook where name like '%"+name+"%'";
        EntityMapping mapping = mappingFactoy.getmapping(MappingFactoy.Guestbook_Mapping);
        List<Object> list = jdbcTemplate.query(sql,mapping);
        return list;
    }

    @Override
    public boolean delete(int id) throws SQLException {
        String sql = "delete from guestbook where id = ?";
        int isRight = jdbcTemplate.update(sql,id);
        return isRight == 1;
    }

    @Override
    public boolean update(String name, String phone, String email, String title, String content, String createdtime,int id)throws SQLException {
        String sql = "update guestbook set name = ?,phone = ?,email = ?,title = ?,content = ?,createdtime = ? where id = ?";
        int isRight = jdbcTemplate.update(sql,name,phone,email,title,content,createdtime,id);
        return isRight == 1;
    }

//    public static void main(String[] args) {
//        GuestbookMapping guestbookMapping = new GuestbookMapping();
//        DBManager dbManager = DBManager.getInstance();
//        Connection conn = dbManager.getConnection();
//        guestbookMapping.setConnection(conn);
//        try {
//            boolean isRight = guestbookMapping.update("yamaha","123123","yamaha@163.com","test","asd","2021-08-25",13);
//            if (isRight == true){
//                System.out.println("ok");
//                conn.commit();
//            }else {
//                System.out.println("no");
//            }
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
//    }
}
